package com.zut.Service.HttpJudgeImpl;

import cn.hutool.json.JSONUtil;
import com.zut.Pojo.Request.CodeEntity;
import com.zut.Pojo.language;
import com.zut.Pojo.problem.Problem;
import com.zut.Pojo.problem.ProblemCase;
import com.zut.Pojo.submissionsBody;
import com.zut.Service.HttpJudge;
import com.zut.dao.ProblemDao;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 样例判断
 */

@Component
@Log4j
public class CaseHttpJudgeImpl extends getHttpResult implements HttpJudge {


    @Autowired
    private ProblemDao problemDao;

    /**
     * 提交运行
     * @param body
     * @return
     */
    @Override
    public Boolean GoJudge(String body) {

        // 对请求体进行空指针判断
        if (body == null) {
            throw new IllegalArgumentException("请求体不能为空");
        }


        // 将请求体转换为CodeEntity对象
        CodeEntity codeEntity = JSONUtil.toBean(body, CodeEntity.class);
        if (codeEntity == null || codeEntity.getProblemID() == null) {
            throw new IllegalArgumentException("请求体解析失败或缺少问题ID");
        }

        Problem problem = problemDao.selectByProblemId(codeEntity.getProblemID());
        if (problem == null) {
            throw new IllegalArgumentException("未找到对应的问题");
        }

        List<ProblemCase> problemCases = problemDao.getAllCase(problem.getId().toString());
        if (problemCases.isEmpty()) {
            log.error("查询不到problemCase!");
            return false;
        }

        int timeLimit = problem.getTimeLimit();
        int memoryLimit = problem.getMemoryLimit();
        int stackLimit = problem.getStackLimit();

        List<submissionsBody> list = problemCases.stream().map(problemCase -> {
            submissionsBody submissionsBody=new submissionsBody();
            submissionsBody.setLanguage_id(language.valueOf(codeEntity.getLanguage()).getId());
            submissionsBody.setSource_code(codeEntity.getSourceCode());
            submissionsBody.setCpu_time_limit(timeLimit);
            submissionsBody.setMemory_limit(memoryLimit);
            submissionsBody.setStack_limit(stackLimit);
            submissionsBody.setStdin(problemCase.getInput());
            submissionsBody.setExpected_output(problemCase.getOutput());
            return submissionsBody;
        }).peek(JSONUtil::toJsonStr).collect(Collectors.toList());


        return getResultBoolean(codeEntity, list);

    }

}
